<template>
	<view class="pages" v-if="viewModel">
		<pages-rate :percent="percent"></pages-rate>
		<view class="pages-line"></view>
		<view style="padding: 20upx;">巡检开始时间：{{dateFormat(date)}}</view>
		<view class="cont" v-if="widget">
			<view class="cont-title">{{widget.title}} <text class="cont-require" v-if="widget.required">*</text></view>
			<view class="cont-intro">检查内容:</view>
			<!-- <view class="select" v-if="widget.type === 'radio'">
				<view class="select-btn" @click="selectClick(widget.answer, item)" v-for="(item, index) in widget.answer" :key="index">{{item.name}}</view>
			</view> -->
			<view class="input" v-if="widget.type === 'input'">
				<view class="input-title">{{widget.intro}}</view>
				<view class="cont-intro" style="margin-top:20px ;margin-bottom:20px">检查情况:</view>
					<view class="uni-list">
						<radio-group @change="radioChange">
							<label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in items" :key="item.value">
								<view>
									<radio :value="item.value" :checked="index === current" />
								</view>
								<view>{{item.name}}</view>
							</label>
						</radio-group>
					</view>
				<input v-show="flagMsg" type="text" @focus="isFocus = true" @blur="isFocus = false" v-model="value" placeholder-class="input-place" class="input-cont" :class="{'input-contact': isFocus}" :placeholder="widget.placeholder" />
				<!-- <view class="input-tips">巡检填报内容需完整无误</view> -->
				<view class="content" v-show="flagMsg">
					<!-- <hlUploadImg ref="hlUploadImg" tapModel="preview" :imgList="oldImgList"></hlUploadImg> -->
					<view v-for="(photo,index) in photoData" :key="index" class="photo">
						<view class="closeA" @tap="deletePhoto(index)">&times;</view>
						<image :src="photo" @click="previewPhoto(photo,photoData)"></image>
					</view>
					<view v-show="!submitButtonStatus" class="btnAddPhoto" @click="btnAddPhoto">+</view>
					<canvas :style="{width:canvasWidth,height:canvasHeight}"  v-show="flagC" canvas-id="myCanvas"></canvas>
				</view>
				<view class="input-submit" @click="nextClick">下一巡检地点</view>
			</view>
		</view>
		<pages-msg v-if="viewIndex == viewModel.length" :userInfo="userInfo"></pages-msg>
	</view>
</template>

<script>
	import pagesRate from './problem-widget/rate'
	import pagesMsg from './problem-widget/msg'
	import testJson from './problem-widget/test.json'
	import hlUploadImg from "@/components/hl-uploadImg/hlUploadImg.vue"
import loginVue from '../login/login.vue'
	export default {
		data() {
			return {
				percent: 0,
				problemList: testJson.problem, // 所有问题
				viewModel: null,  //需展现问题
				widget: {}, // 问题对象
				viewIndex: 0 ,// 当前所处问题下标
				value: '',
				problemModel: null ,// 已完成问题
				isFocus: false,
				items: [{
							value: '0',
							name: '正常',
							checked: 'true'
						},
						{
							value: '1',
							name: '异常'
						}],
				current: 0,
				flagC: false,
				flag: false,
				flagMsg:false,
				submitButtonStatus: false,
				photoData: [],
				photoDataTemp: [],
				photoArray: [],
				canvasWidth: "1920px",
				canvasHeight: "1080px",
				photoIndex: 0,
				imgList:[],
				date: new Date().toISOString(),//现在时间
				stationName:"",
				userName:""
			}
		},
		components: {
			pagesRate,
			pagesMsg,
			hlUploadImg
		},
		onLoad() {
			this.init()
			let _this = this;
			//实时获取时间
			// setInterval(function() {
			// _this.date = Date.parse(new Date());
			// }, 1000);
			uni.getStorage({
				key: 'userInfo',
				success(res) {
					var userInfomsg = JSON.parse(JSON.stringify(res.data));
					console.log('用户信息')
					console.log(userInfomsg);
					// this.deptId=userInfomsg.deptId
					_this.deptName=userInfomsg.deptName
					_this.deptNo=userInfomsg.deptNo
					_this.userName=userInfomsg.username
					if (userInfomsg.username == 'shannan') {
						//善南  善南闸
						_this.stationName="善南闸"
					}
					if (userInfomsg.username == 'jiewei') {
						//界圩闸
						_this.stationName="界圩闸"
					}
					if (userInfomsg.username == 'dingbei') {
						//叮北闸
						_this.stationName="叮北闸"
					}
				}
			});
		},
		methods: {
			getUserInfo(){
				let _this = this;
				//实时获取时间
				// setInterval(function() {
				// _this.date = Date.parse(new Date());
				// }, 1000);
				uni.getStorage({
					key: 'userInfo',
					success(res) {
						var userInfomsg = JSON.parse(JSON.stringify(res.data));
						console.log('用户信息')
						console.log(userInfomsg);
						// this.deptId=userInfomsg.deptId
						_this.deptName=userInfomsg.deptName
						_this.deptNo=userInfomsg.deptNo
						_this.userName=userInfomsg.username
						if (userInfomsg.username == 'shannan') {
							//善南  善南闸
							_this.stationName="善南闸"
						}
						if (userInfomsg.username == 'jiewei') {
							//界圩闸
							_this.stationName="界圩闸"
						}
						if (userInfomsg.username == 'dingbei') {
							//叮北闸
							_this.stationName="叮北闸"
						}
					}
				});
			},
			async init() {
				this.viewModel = JSON.parse(JSON.stringify(this.problemList))
				this.widget = this.viewModel[this.viewIndex]
			},
			dateFormat(time) {
				    let date = new Date(time);
				    let year = date.getFullYear();
				    // 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
				    let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
				    let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
				    let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
				    let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
				    let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
				    // 拼接
				    return year + "年" + month + "月" + day + "日" + hours + ":" + minutes + ":" + seconds;
				    // return year + "-" + month + "-" + day;
				},
			dateFormatTime(time) {
					let date = new Date(time);
					let year = date.getFullYear();
					// 在日期格式中，月份是从0开始的，因此要加0，使用三元表达式在小于10的前面加0，以达到格式统一  如 09:11:05
					let month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
					let day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
					let hours = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
					let minutes = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
					let seconds = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
					// 拼接
					return year + "" + month + "" + day + "" + hours + "" + minutes + "" + seconds;
					// return year + "-" + month + "-" + day;
				},
			selectClick(data, item) {
				this.radioHandle(data, item)
			},
			radioChange: function(evt) {
			            for (let i = 0; i < this.items.length; i++) {
			                if (this.items[i].value === evt.detail.value) {
			                    this.current = i;
								if(this.current===1){
									// console.log(this.current)
									this.flagMsg=true
									this.photoArray=[];
									this.photoData=[];
								}else{
									this.flagMsg=false
								}
			                    break;
			                }
			            }
			        },
			recData(data, model, list) {
				if (data.length > 0) {
					data.forEach(item => {
						if (model && item.parentId === model.id) {
							var findModel = list.find(r => r === item.parentId)
							if (!findModel) list.push(item.parentId)
							if (item.type === 'radio') {
								var arrList = item.answer.filter(r => r.id)
								if (arrList.length > 0) {
									arrList.forEach(rr => {
										this.recData(data, rr, list)
									})
								}
							}
						}
					})
				}
				return list
			},
			nextClick() {
				// this.getUserInfo()
				if(this.current===1&& !this.value){
					return uni.showToast({
							title: '请填写必填项',
							icon: 'none',
							duration: 2000
						})
				}
				if(this.current===1){  //用户选择巡检点异常  点击下一巡检点时提交巡检异常信息到后台，并上传异常图片	
					//上传图片
					let inspectionId= this.stationName+this.dateFormatTime(this.date)
					//从当前数据中提取非网络图片的路径
					var localImages = this.photoData
					console.log('本地图片数')
					console.log(localImages)
					// this.$upload.uploadImg(this.photoData, inspectionId, res => {
					var i = 0
					if (localImages.length !== 0) {
						this.$upload.uploadImg(localImages, inspectionId, res => {
							i++;
							// console.log(i)
							// console.log(localImages.length)
							if (i == localImages.length) {
								let pages = getCurrentPages(); // 当前页面
								let beforePage = pages[pages.length - 2]; // 上一页
								// uni.navigateBack({
								// 		delta: 1, //返回层数，2则上上页
								// 		animationType: 'pop-out',
								// 		animationDuration: 300,
								// 	}),
									uni.showToast({
										title: `提交成功`
									})
							}
						});
					
					}
				}
				//提交巡检信息
				//提交巡检信息
				this.$myrequest({
					url: '/tpoint/add',
					method: 'POST',
					data: {
						taskId: this.stationName+this.dateFormatTime(this.date),
						name: this.userName,
						point: this.widget.title,
						startTime: this.date,
						stopTime: new Date().toISOString(),
						status: this.current,
						info: this.value,
						
					}
				}).then(res => {
					//跳转页面 当首页含有tarbar的时候使用下面方式跳转
					uni.showToast({
							title: '巡检点信息提交成功',
							icon: 'none',
							duration: 2000
						})
				});
				this.current=0
				this.flagMsg=false
				this.viewIndex += 1
				this.widget = this.viewModel[this.viewIndex]
				this.percent = parseInt(this.viewIndex / this.viewModel.length * 100)
				if(this.percent==100){
					console.log(this.percent)
					//提交巡检总记录信息
					this.$myrequest({
						url: '/tinspectionReport/add',
						method: 'POST',
						data: {
							taskId: this.stationName+this.dateFormatTime(this.date),
							place: this.stationName,
							route: "日常巡检",
							taskType: "日常巡检",
							startTime: this.date,
							reportTitle: "日常巡检",
							reportTitleSub:this.stationName,
							stopTime: new Date().toISOString(),
							taskPerson: this.userName,
						}
					}).then(res => {
						uni.showToast({
								title: '本次巡检完成',
								icon: 'none',
								duration: 2000
							})
					});
				}
				this.value = ''
			},
			// 添加图片事件
			btnAddPhoto() {
				// this.photoIndex = 0;
				let ctx = uni.createCanvasContext('myCanvas');
				uni.chooseImage({
					count: 9,
					sourceType: ['album', 'camera'],
					success: res => {
						this.photoArray = res.tempFilePaths;
						uni.getImageInfo({
							src: res.tempFilePaths[0],
							success: function(image) {
								this.canvasWidth=image.width;
								this.canvasHeight=image.height;
							}
						});
						uni.showLoading({
							title: "图片加载中..."
						})
						this.callAddWaterMart();
						// this.flagC = true
						// this.photoData.push(res.tempFilePath);
						// callback();
						// uni.hideLoading()
					}
				})
			},
			// 调用添加水印的函数
			callAddWaterMart() {
				this.addWaterMark(() => {
					if (this.photoIndex < this.photoArray.length - 1) {
						this.photoIndex++;
						this.callAddWaterMart()
						uni.hideLoading()
					} else {
						uni.hideLoading()
					}
				})
			},
			//添加水印
			addWaterMark(callback) {
				this.flagC = true,
				uni.getImageInfo({
					src: this.photoArray[this.photoIndex],
					success: res => {
						this.canvasWidth = `${res.width}px`;
						this.canvasHeight = `${res.height}px`;
						var ctx = uni.createCanvasContext('myCanvas',this);
						// console.log(res.width)
						// console.log(res.height)
						ctx.clearRect(0, 0, res.width, res.height);
						ctx.beginPath();
						ctx.drawImage(this.photoArray[this.photoIndex], 0, 0, res.width, res.height);
			
						// var timeStr = getDateTime.dateTimeStr(
						// 	'y-m-d h:i:s'); // y:年 m:月 d:日 h:时 i:分 s:秒 中间的分割符号可更改
						// 为图片添加水印
						// ctx.translate(0, res.height);
						// ctx.rotate(45 * Math.PI / 180);
						// let horizontal = res.width / 4;
						// let vertical = res.height / 3;
						// console.log(horizontal)
						// console.log(vertical)
			// 			for (let i = 0; i <= 3; i++) {
			// 				for (let j = 0; j <= 3; j++) {
			// 					ctx.beginPath();
			// 					ctx.setFontSize(25);
			// 					ctx.setFillStyle("rgba(255,255,255,0.4)");
			// 					ctx.setStrokeStyle("rgba(40, 40, 40, 1)");
			// 					ctx.fillText("上报项目：" + this.valiFormData.projectName, 0, -100);
			// 					ctx.fillText("项目内容：" + this.valiFormData.contentName, 0, -70);
			// 					ctx.fillText("上报人员：" + this.valiFormData.realName, 0, -40);
			// 					ctx.fillText("上报时间：" + timeStr, 0, -10);
			
			// 				}
			// 			}
			
						// 开始绘制添加水印的图片并显示在页面中
						ctx.draw(false, () => {
							setTimeout(() => {
								// console.log("asdf");
								uni.canvasToTempFilePath({
									canvasId: "myCanvas",
									success: res => {
										// console.log(res.tempFilePath)
										this.flagC = false
										this.photoData.push(res.tempFilePath);
										callback();
									}
								},this)
								// 在自定义组件内 需要传递第二参数 this canvas才生效
							}, 1000)
						});
					}
				})
			},
			
			// 预览图片
			previewPhoto(url, list) {
				uni.previewImage({
					current: url,
					urls: list.map(item => item)
				})
			},
			
			// 删除图片
			deletePhoto(index) {
				this.photoArray.splice(index, 1);
				this.photoData.splice(index, 1);
				// console.log(this.photoArray)
			},
		}
	}
</script>

<style lang="scss" scoped>
	.pages {
		&-line {
			height: 50rpx;
		}
		.cont {
			width: 750rpx;
			padding: 0 30rpx;
			box-sizing: border-box;
			&-title {
				font-size: 40rpx;
				color: #222222;
				font-weight: bold;
				height: 80rpx;
				line-height: 80rpx;
			}
			&-intro {
				font-size: 32rpx;
				color: #868686;
			}
			&-require {
				margin-left: 5rpx;
				color: red;
			}
		}
		.select {
			margin-top: 120rpx;
			&-btn {
				width: 600rpx;
				height: 88rpx;
				margin: 0 auto;
				margin-bottom: 40rpx;
				border-radius: 60rpx;
				text-align: center;
				line-height: 88rpx;
				font-size: 32rpx;
				color: #222222;
				border: 1rpx solid #CCCCCC;
			}
		}
		.input {
			margin-top: 30rpx;
			&-title {
				font-size: 26rpx;
				color: #868686;
			}
			&-cont {
				margin-top: 30rpx;
				height: 100rpx;
				line-height: 100rpx;
				font-size: 32rpx;
				color: #343434;
				border-bottom: 1rpx solid #f6f7f8;
			}
			&-contact {
				border-bottom: 1rpx solid #222;
			}
			&-tips {
				margin-top: 20rpx;
				font-size: 28rpx;
				color: #868686;
			}
			&-place {
				color: #c9c9c9;
			}
			&-submit {
				width: 600rpx;
				height: 88rpx;
				margin: 0 auto;
				margin-top: 80rpx;
				background-color: #0A58F6;
				border-radius: 60rpx;
				text-align: center;
				line-height: 88rpx;
				font-size: 32rpx;
				color: #fff;
				font-weight: bold;
			}
		}
		.content {
			padding: 20upx;
		}
		
		// .photo,
		.photo image {
			display: inline-block;
			width: 220upx;
			height: 220upx;
		}
		
		.btnAddPhoto {
			width: 220upx;
			height: 220upx;
			border: dashed 1px #aaa;
			display: flex;
			justify-content: center;
			align-items: center;
			font-size: 50upx;
		}
		
		canvas {
			border: solid 1px gray;
			position: absolute;
			left: 50000upx;
		
		}
	}
	// .upBox{
	// 	width: 100%;
	// 	padding: 0 30upx;
	// 	display: flex;
	// 	flex-direction: column;
	// 	align-items: stretch;
	// }
	// .rowTitle{
	// 	margin-bottom: 20upx;
	// 	margin-top: 40upx;
	// 	font-size: 28upx;
	// }
	// .mark{
	// 	font-size: 28upx;
	// 	font-weight: bold;
	// }
	// .markDetail{
	// 	font-size: 28upx;
	// 	color: #333333;
	// }
	// .myBtn{
	// 	margin: 0;
	// 	padding: 0;
	// 	background:#409EFF;
	// 	color: #FFFFFF;
	// 	box-sizing: border-box;
	// 	border: none;
	// }
</style>
